package y1s.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import y1s.data.Data;
import y1s.data.Memcache;
import y1s.servlet.AgeDomain;
import y1s.servlet.AlexaUpdate;
import y1s.servlet.GetPage;
import y1s.servlet.GetTrackIp;
import y1s.servlet.GooglePageRank;
import y1s.servlet.Whois;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

@SuppressWarnings("serial")
public class SearchWhoisServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");

		String name = Utils.fomatDomain(req.getParameter("name"));
		if(Utils.checkDomain(name))
		{
			DBCollection coll = Data.data("domain");
	
			DBObject domain = coll.findOne(new BasicDBObject("name",name));
	
			if(domain != null)
			{
				resp.setHeader( "Cache-Control", "public, max-age=86400");
				resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
				req.setAttribute("domain", domain);
				req.setAttribute("name", name);
				try {
					req.getRequestDispatcher("/whois.jsp").forward(req, resp);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				Random generator = new Random();
				int r = generator.nextInt(100000);
				BasicDBObject domains = new BasicDBObject();
				domains.put("name", name);
				domains.put("update", new Date().getTime());
				domains.put("random", r);

				try {
					new GetPage(domains);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new GooglePageRank(domains);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new AgeDomain(domains);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new AlexaUpdate(domains);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new Whois(domains);
				} catch (Exception e) {
					// TODO: handle exception
				}
				try {
					new GetTrackIp(domains);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				try {
					Thread.sleep(5000);
					coll.save(domains);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Memcache.setMemcache("last-update", domains.get("name").toString());
				
				resp.sendRedirect("/w/"+name);
			}
		} else {
			resp.getWriter().println("domain does not exist !");
		}
	}

}
